<?php

namespace App\Manage;


use App\Models\SiteConfig;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class SiteConfigManage extends Manage
{


    // 父级
    // 添加，修改，删除，列表，停用 操作
    // TODO 操作日志

    // 配置
    public function setting($myUser, $options = [])
    {
        $list = Config::get('site');

        return $list;
    }


    // 获取配置
    public function config($myUser, $options = [])
    {
        $model = new SiteConfig();
        $list  = $model->getConfigCache([]);

        return $list;
    }

    // 获取配置
    public function lists($myUser, $options = [])
    {
        $model = new SiteConfig();
        $list  = $model->getList([], 0, 'weigh DESC');

        return $list;
    }

    // 保存配置
    public function save($myUser, $options = [])
    {

        // 参数
        $is_admin_log = $options['is_admin_log'] ?? 0;


        $opt  = $this->option();
        $data = $opt->getData();
        $data = $opt->filterNull($data);
        if(empty($data)){
            //return $this->_returnFail("请传递需要修改的数据！");
            return $this->_returnFail("send_data_to_be_modify");
        }

        // 获取配置
        $kField = 'field';
        $kField = 'name';
        $model  = new SiteConfig();
        $list   = $model->get()->toArray();
        $list   = array_column($list, null, $kField);
        $table  = 'site_config';


        // 保存数据
        DB::beginTransaction();
        try{
            foreach($data as $field => $val){
                $info = $list[$field] ?? [];

                // 添加
                if(empty($info)){
                    $setArr = [$kField => $field, "value" => $val];
                    $result = DB::table($table)->insert($setArr);
                } else{
                    // 修改
                    $result = DB::table($table)->where(['id' => $info['id']])->update(["value" => $val]);
                }
                if($result === false){
                    //throw  new \Exception('保存配置信息失败！！');
                    throw  new \Exception('failed_to_save_information');
                }
            }

            DB::commit();
        } catch(\Exception $e){
            DB::rollBack();

            return $this->_returnFail($e->getMessage());
        }

        // 管理员日志
        /*if($is_admin_log){
            $this->addAdminLog($myUser['id'], '修改自己的个人资料', '');
        }*/


        // 删除缓存
        $model->deleteCacheList($list);

        return true;
    }

}


